package com.eeepay.eeepay_v2.activity;

import android.os.Handler;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.eeepay.eeepay_v2.R;
import com.eeepay.eeepay_v2.model.UserInfo;
import com.eeepay.eeepay_v2.model.WithdrawCashInfo;
import com.eeepay.eeepay_v2.util.Constant;
import com.eeepay.eeepay_v2.util.GrpcUtils;
import com.eeepay.eeepay_v2.util.MathUtils;
import com.eeepay.eeepay_v2.util.RateUtils;
import com.eeepay.eeepay_v2.view.TipMsgDialog;
import com.eeepay.v2_library.log.LogUtils;
import com.eeepay.v2_library.ui.ABBaseActivity;
import com.eeepay.v2_library.view.TitleBar;

import java.math.BigDecimal;

import cn.eeepay.api.grpc.nano.WithdrawCashApiServiceGrpc;
import cn.eeepay.api.grpc.nano.WithdrawCashProto;
import io.grpc.ManagedChannel;

/**
 * 描述：分润提现
 * 作者：zhuangzeqin
 * 时间: 2017/5/3-17:08
 * 邮箱：zzq@eeepay.cn
 */
public class ShareBenefitTXActivity extends ABBaseActivity implements View.OnClickListener {
    private final static String TAG = ShareBenefitTXActivity.class.getSimpleName();
    private TitleBar titleBar;//标题栏
    private TextView tv_txmoney;//可提现金额
    private TextView tv_tixian_all;//全部提现
    private TextView tv_hint;//提现温馨提示语
    private EditText et_money;//提现金额输入框
    private Button btn_tx;//提现按钮

    private String iniValue = "0.00";//初始化数据0.00

    private WithdrawCashInfo withdrawCashInfo = null;

    //    private final int FRISTAGENTREQUEST_TASKID = 1001;//1 是否为一级代理商
    private final int GETWITHDRAWCASHINFOT_TASKID = 1002;//2 获取可提现的余额,手续费,最低提现金额等信息
    private final int WITHDRAWCASH_TASKID = 1003;//3 体现操作

    private TipMsgDialog tipMsgDialog;
//    private boolean isFristAgent = false;//是否为一级代理商；默认为false　即不是

    @Override
    protected int getLayoutId() {
        return R.layout.activity_share_benefit_tx;
    }

    @Override
    protected void initWidget() {
        /** 标题栏设置**/
        titleBar = getViewById(R.id.title_bar);
        titleBar.setShowRight(View.VISIBLE);
        titleBar.setRightTextView("账号记录");
        titleBar.setRightTextColor(R.color.unify_grounding_white);

        tv_txmoney = getViewById(R.id.tv_txmoney);
        tv_tixian_all = getViewById(R.id.tv_tixian_all);//全部提现
        et_money = getViewById(R.id.et_money);//请输入提现金额
        tv_hint = getViewById(R.id.tv_hint);
        btn_tx = getViewById(R.id.btn_tx);//提现按钮

        tipMsgDialog = new TipMsgDialog(mContext);

        //初始化进来；第一步要判断是否为一级代理商；如果是则进行下一步操作；如果不是给出相应的提示语；提示语由后台提供
//        sendHttpRequest(FRISTAGENTREQUEST_TASKID);
        //获取获取 ****可提现的余额,手续费,最低提现金额等信息***
        sendHttpRequest(GETWITHDRAWCASHINFOT_TASKID);

    }

    /**
     * 初始化数据；数据从实体bean 获取
     *
     * @param withdrawCashInfo
     */
    private void inintData(WithdrawCashInfo withdrawCashInfo) {
        //可提现金额
        String value = String.format("可提现金额:%s元", MathUtils.twoNumber(withdrawCashInfo.getAvaliBalance().toString()));
        tv_txmoney.setText(value);
        settingTipMsg(iniValue, iniValue);
    }

    /**
     * 提现温馨提示语显示设置
     */
    private void settingTipMsg(String feeRateValue, String str_tv_txmoney) {
        //可提现手续费**元,即到账金额为=输入提现金额-可提现手续费
        double BlanceValue = Double.parseDouble(str_tv_txmoney) - Double.parseDouble(feeRateValue);
        String tip = String.format("提现手续费为%s元,到账金额为%s元", MathUtils.twoNumber(feeRateValue), MathUtils.twoNumber(BlanceValue));
        tv_hint.setText(tip);
    }


    @Override
    protected void eventOnClick() {
        //账号记录
        titleBar.setRightOnClickListener(new TitleBar.RightBtnOnClickListener() {
            @Override
            public void onRightClick(View view) {
                goActivity(WithdrawalRecordActivity.class);
            }
        });
        //提现操作
        btn_tx.setOnClickListener(this);
        //提现全部
        tv_tixian_all.setOnClickListener(this);
        /**
         * 监听输入的文本
         */
        et_money.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                String txValue = s.toString().trim();
                if (!TextUtils.isEmpty(txValue)) {
                    if (withdrawCashInfo != null) {
                        BigDecimal money = new BigDecimal(txValue);
                        BigDecimal rateDecimal = RateUtils.txRate(withdrawCashInfo, money);
                        //可提现手续费**元,即到账金额为=输入提现金额-可提现手续费
                        settingTipMsg(rateDecimal.toString(), money.toString());
                    }
                } else {
                    settingTipMsg(iniValue, iniValue);
                }
            }
        });
    }

    /**
     * 发送网络请求
     *
     * @param taskId
     */
    @Override
    protected void sendHttpRequest(int taskId) {
        showProgressDialog();
        GrpcUtils.getInstance().doGrpcTask(Constant.URL.URL, Constant.URL.PORT, taskId, new GrpcUtils.AsyncTaskListener() {
            @Override
            public Object doInBack(ManagedChannel channel, int taskId) {
                WithdrawCashApiServiceGrpc.WithdrawCashApiServiceBlockingStub sub = WithdrawCashApiServiceGrpc.newBlockingStub(channel);
                switch (taskId) {
//                    case FRISTAGENTREQUEST_TASKID://1 是否为一级代理商
//                        WithdrawCashProto.FristAgentRequest fristAgentRequest = new WithdrawCashProto.FristAgentRequest();
//                        fristAgentRequest.agentNo = UserInfo.getUserInfo2SP().getAgentNo();//代理商编号
//                        return sub.isFristAgent(fristAgentRequest);
                    case GETWITHDRAWCASHINFOT_TASKID://2 获取可提现的余额,手续费,最低提现金额等信息
                        WithdrawCashProto.WithdrawCashInfoRequest infoRequest = new WithdrawCashProto.WithdrawCashInfoRequest();
                        infoRequest.agentNo = UserInfo.getUserInfo2SP().getAgentNo();//代理商编号
                        return sub.getWithdrawCashInfo(infoRequest);
                    case WITHDRAWCASH_TASKID://3 提现操作
                        WithdrawCashProto.WithdrawCashRequest cashRequest = new WithdrawCashProto.WithdrawCashRequest();
                        cashRequest.agentNo = UserInfo.getUserInfo2SP().getAgentNo();//代理商编号
                        cashRequest.money = et_money.getText().toString().trim();//提现金额
                        cashRequest.userId = UserInfo.getUserInfo2SP().getUserNo();//用户编号
                        return sub.withdrawCash(cashRequest);
                }
                return null;
            }

            @Override
            public void updateUI(Object result, int taskId) {
                dismissProgressDialog();
                if (result == null) {
                    showToast("获取失败，请稍后重试");
                    return;
                }
                switch (taskId) {
                   /* case FRISTAGENTREQUEST_TASKID://1 一级代理商
                        WithdrawCashProto.FristAgentResponse fristAgentResponse = (WithdrawCashProto.FristAgentResponse) result;
                        if (fristAgentResponse == null) return;
                        boolean status = fristAgentResponse.baseResponse.status;
                        if (!status) {
                            showToast(fristAgentResponse.baseResponse.msg);
                            return;
                        }
                        isFristAgent = fristAgentResponse.isFristAgent;//是否为一级代理商
                        if (isFristAgent == false) {
                            showToast("您不是一级代理商；暂时无法提供相应的服务");
                            finish();//非一级不能进入提现页;直接关闭
                        } else {
                            //如果是一级代理商；则下一步操作获取获取 ****可提现的余额,手续费,最低提现金额等信息***
                            sendHttpRequest(GETWITHDRAWCASHINFOT_TASKID);
                        }
                        break;*/
                    case GETWITHDRAWCASHINFOT_TASKID://2 获取可提现的余额,手续费,最低提现金额等信息
                        WithdrawCashProto.WithdrawCashInfoResponse cashInfoResponse = (WithdrawCashProto.WithdrawCashInfoResponse) result;
                        if (cashInfoResponse == null) return;
                        if (!cashInfoResponse.baseResponse.status) {
                            showToast(cashInfoResponse.baseResponse.msg);
                            return;
                        }
                        withdrawCashInfo = new WithdrawCashInfo();
                        if (!TextUtils.isEmpty(cashInfoResponse.avaliBalance))
                            withdrawCashInfo.setAvaliBalance(new BigDecimal(cashInfoResponse.avaliBalance));//可用余额
                        String rateType = cashInfoResponse.rateType;
                        withdrawCashInfo.setRateType(rateType);//费率类型:1-每笔固定金额，2-扣率，3-扣率带保底封顶，4-扣率+固定金额,5-单笔阶梯 扣率
                        if (!TextUtils.isEmpty(cashInfoResponse.singleNumAmount))
                            withdrawCashInfo.setSingleNumAmount(new BigDecimal(cashInfoResponse.singleNumAmount));//每笔固定值
                        if (!TextUtils.isEmpty(cashInfoResponse.rate))
                            withdrawCashInfo.setRate(new BigDecimal(cashInfoResponse.rate));//扣率
                        if (!TextUtils.isEmpty(cashInfoResponse.capping))
                            withdrawCashInfo.setCapping(new BigDecimal(cashInfoResponse.capping));//封顶
                        if (!TextUtils.isEmpty(cashInfoResponse.safeLine))
                            withdrawCashInfo.setSafeLine(new BigDecimal(cashInfoResponse.safeLine));// 保底
                        if (!TextUtils.isEmpty(cashInfoResponse.ladder1Rate))
                            withdrawCashInfo.setLadder1Rate(new BigDecimal(cashInfoResponse.ladder1Rate));// 阶梯区间1费率
                        if (!TextUtils.isEmpty(cashInfoResponse.ladder1Max))
                            withdrawCashInfo.setLadder1Max(new BigDecimal(cashInfoResponse.ladder1Max));// 阶梯区间1上限
                        if (!TextUtils.isEmpty(cashInfoResponse.ladder2Rate))
                            withdrawCashInfo.setLadder2Rate(new BigDecimal(cashInfoResponse.ladder2Rate));//.....同上
                        if (!TextUtils.isEmpty(cashInfoResponse.ladder2Max))
                            withdrawCashInfo.setLadder2Max(new BigDecimal(cashInfoResponse.ladder2Max));
                        if (!TextUtils.isEmpty(cashInfoResponse.ladder3Rate))
                            withdrawCashInfo.setLadder3Rate(new BigDecimal(cashInfoResponse.ladder3Rate));
                        if (!TextUtils.isEmpty(cashInfoResponse.ladder3Max))
                            withdrawCashInfo.setLadder3Max(new BigDecimal(cashInfoResponse.ladder3Max));
                        if (!TextUtils.isEmpty(cashInfoResponse.ladder4Rate))
                            withdrawCashInfo.setLadder4Rate(new BigDecimal(cashInfoResponse.ladder4Rate));
                        if (!TextUtils.isEmpty(cashInfoResponse.ladder4Max))
                            withdrawCashInfo.setLadder4Max(new BigDecimal(cashInfoResponse.ladder4Max));
                        LogUtils.d(TAG, withdrawCashInfo.toString());
                        inintData(withdrawCashInfo);
                        break;
                    case WITHDRAWCASH_TASKID://3 提现操作
                        WithdrawCashProto.WithdrawCashResponse cashResponse = (WithdrawCashProto.WithdrawCashResponse) result;
                        if (cashResponse == null) return;
                        if (!cashResponse.baseResponse.status) {
//                            showToast(cashResponse.baseResponse.msg);
                            //失败的提示语

                            tipMsgDialog.setTipMsg(cashResponse.baseResponse.msg);
                            tipMsgDialog.show();
                            return;
                        } else {
                            showToast(cashResponse.baseResponse.msg);//成功的提示语
                            //等1S后返回，否则后台数据没刷新，等1S也不一定能刷新 --zw 2017年5月8日15:57:12
                            new Handler().postDelayed(new Runnable() {
                                @Override
                                public void run() {
                                    setResult(RESULT_OK);
                                    finish();
                                }
                            }, 1000);

                        }
                        break;
                }
            }
        });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_tx://提现操作
                /**
                 * 1 提现金额不能为空
                 * 2 提现金额不能小于手续费；也不能大于能提现的金额
                 */
                String et_moneyValue = et_money.getText().toString().trim();
                if (TextUtils.isEmpty(et_moneyValue)) {
                    showToast("提现金额不能为空");
                    return;
                } else {
                    BigDecimal money = new BigDecimal(et_moneyValue);
                    BigDecimal fee = RateUtils.txRate(withdrawCashInfo, money);
                    // 1 提现金额小于手续费
                    if (!TextUtils.isEmpty(fee.toString()) &&
                            Double.parseDouble(et_moneyValue) <= Double.parseDouble(fee.toString())) {
                        showToast("提现金额小于手续费");
                        return;
                    }//2 提现金额不可超过可提现金额
                    else if (Double.parseDouble(et_moneyValue) > Double.parseDouble(withdrawCashInfo.getAvaliBalance().toString())) {
                        showToast("提现金额超过可提现金额");
                        return;
                    } else {//3 发起提现操作
                        sendHttpRequest(WITHDRAWCASH_TASKID);
                    }
                }
                break;
            case R.id.tv_tixian_all://提现全部
                if (withdrawCashInfo == null) return;
                et_money.setText(MathUtils.twoNumber(withdrawCashInfo.getAvaliBalance().toString()));
                et_money.setSelection(et_money.getText().length());
                //取消自动获取焦点
                et_money.clearFocus();
                InputMethodManager imm = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
                imm.hideSoftInputFromWindow(et_money.getWindowToken(), 0);
                et_money.setFocusable(true);
                et_money.setFocusableInTouchMode(true);
                break;
        }
    }
}
